﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Galaktika.BI.Runtime.Services;
using System.ComponentModel;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Runtime;
using Galaktika.BI.Silverlight.Controls.MemberChoice.Info;
using Galaktika.BI.Silverlight.Controls.General;
using System.Threading;

namespace Galaktika.BI.Silverlight.Controls.MemberChoice
{
    public partial class MemberChoicePopUp : UserControl, IBindableObject, IEditableObject
    {
        MemberChoiceControl m_ChoiceControl = null;

        public MemberChoicePopUp()
        {
            InitializeComponent();

            this.Height = 22;
            this.VerticalAlignment = VerticalAlignment.Top;

            m_Popup.BeforePopUp += new EventHandler(m_Popup_BeforePopUp);

            LayoutRoot.Children.Add(m_Popup);
        }

        void m_Popup_BeforePopUp(object sender, EventArgs e)
        {
            if (m_ChoiceControl == null)
            {
                m_ChoiceControl = new MemberChoiceControl();
                m_ChoiceControl.ApplySelection += new EventHandler(m_ChoiceControl_ApplySelection);
                m_ChoiceControl.CancelSelection += new EventHandler(m_ChoiceControl_CancelSelection);
                m_Popup.ContentControl = m_ChoiceControl;
            }

            if (m_NeedReload)
            {
                m_ChoiceControl.Connection = m_AConnection;
                m_ChoiceControl.CubeName = m_ACubeName;
                m_ChoiceControl.HierarchyName = m_AHierarchyName;
                m_ChoiceControl.Context = m_Context;

                m_ChoiceControl.MultiSelect = m_AMultiSelect;
                m_ChoiceControl.UseStepLoading = m_AUseStepLoading;
                m_ChoiceControl.Step = m_AStep;
                m_ChoiceControl.StartLevelUniqueName = m_AStartLevelUniqueName;
                m_ChoiceControl.StartMemberUniqueName = m_AStartMemberUniqueName;

                m_ChoiceControl.Initialize();
                m_NeedReload = false;
            }
        }

        void m_ChoiceControl_CancelSelection(object sender, EventArgs e)
        {
            m_Popup.IsDropDownOpen = false;
        }

        void m_ChoiceControl_ApplySelection(object sender, EventArgs e)
        {
            UpdatePopUpText();

            m_Popup.IsDropDownOpen = false;
        }

        private bool LogException(Exception ex)
        {
            IOutputService log = (IOutputService)Context.Services.GetService(typeof(IOutputService));
            if (log != null)
            {
                log.WriteException(ex);
                return true;
            }
            return false;
        }

        void UpdatePopUpText()
        {
            if (m_ChoiceControl.SelectedInfo != null && m_ChoiceControl.SelectedInfo.Count > 0)
            {
                //Если выбрано более одного элемента, то это однозначно множественный выбор
                if (m_ChoiceControl.SelectedInfo.Count > 1)
                    m_Popup.Text = "<Multi Select>"; //"<Множественный выбор>";
                else
                {
                    MemberChoiceSettings cs = m_ChoiceControl.SelectedInfo[0];
                    if (cs != null)
                    {
                        if (cs.SelectState != SelectStates.Selected_Self)
                            m_Popup.Text = "<Multi Select>"; //"<Множественный выбор>";
                        else
                        {
                            m_Popup.Text = cs.Caption;
                            //m_Popup.ToolTip = cs.Caption + " : " + cs.UniqueName;
                        }
                    }
                }
            }

            String set = String.Empty;
            if (m_ChoiceControl.SelectedInfo != null)
            {
                set = m_ChoiceControl.SelectedSet;
            }

            try
            {
                //Сохраняем в глобальную переменную
                IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
                if (context != null && !String.IsNullOrEmpty(AVariableToMDXSet))
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(
                        state => context.ModifyVariable(this.Context, AVariableToMDXSet, set)));
                }
            }
            catch (Exception ex)
            {
                if (!LogException(ex))
                    throw ex;
            }
        }
        PopUpContainerControl m_Popup = new PopUpContainerControl();

        #region IBindableObject Members

        IBindingContext m_Context = null;
        public IBindingContext Context
        {
            get
            {
                return m_Context;
            }
            set
            {
                m_Context = value;
                m_NeedReload = true;
            }
        }


        private IDictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new SafeDictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion

        #region IEditableObject Members

        public void BeginEdit()
        {
        }

        public void CancelEdit()
        {
        }

        public void EndEdit()
        {
            m_NeedReload = true;
        }

        #endregion

        bool m_NeedReload = true;

        #region Свойства для настройки на OLAP
        private String m_AConnection = String.Empty;
        /// <summary>
        /// Описание соединения с БД
        /// </summary>
        public String AConnection
        {
            get
            {
                return m_AConnection;
            }
            set
            {
                m_AConnection = value;
                m_NeedReload = true;
            }
        }

        private string m_ACubeName;
        /// <summary>
        /// Имя OLAP куба
        /// </summary>
        public String ACubeName
        {
            get
            {
                return m_ACubeName;
            }
            set
            {
                m_ACubeName = value;
                m_NeedReload = true;
            }
        }

        private string m_AHierarchyName;
        /// <summary>
        /// Имя иерархии измерения
        /// </summary>
        public String AHierarchyName
        {
            get
            {
                return m_AHierarchyName;
            }
            set
            {
                m_AHierarchyName = value;
                m_NeedReload = true;
            }
        }
        #endregion Свойства для настройки на OLAP

        #region Частичная загрузка
        private int m_AStep = 0;
        /// <summary>
        /// Шаг при частичной загрузке ("Задает шаг, используемый при частичной загрузке элементов")
        /// </summary>
        public int AStep
        {
            get
            {
                return m_AStep;
            }
            set
            {
                m_AStep = value;
                m_NeedReload = true;
            }
        }

        private bool m_AUseStepLoading;
        /// <summary>
        /// Использование частичной загрузки ("Флаг указывает необходимость использования частичной загрузки элементов")
        /// </summary>
        public bool AUseStepLoading
        {
            get
            {
                return m_AUseStepLoading;
            }
            set
            {
                m_AUseStepLoading = value;
                m_NeedReload = true;
            }
        }
        #endregion Частичная загрузка

        /// <summary>
        /// Режим выбора: true - множественный выбор, false - одиночный выбор
        /// </summary>
        private bool m_AMultiSelect = true;
        public bool AMultiSelect
        {
            set
            {
                m_AMultiSelect = value;
                m_NeedReload = true;
            }
            get
            {
                return m_AMultiSelect;
            }
        }

        private string m_AStartMemberUniqueName;
        /// <summary>
        /// Уникальное имя элемента, дочерние которого элементы будут отображаться в дереве
        /// </summary>
        public string AStartMemberUniqueName
        {
            set
            {
                m_AStartMemberUniqueName = value;
                m_NeedReload = true;
            }
            get
            {
                return m_AStartMemberUniqueName;
            }
        }

        private string m_AStartLevelUniqueName;
        /// <summary>
        /// Уникальное имя уровня, начиная с которого элементы будут отображаться в дереве
        /// </summary>
        public string AStartLevelUniqueName
        {
            get
            {
                return m_AStartLevelUniqueName;
            }
            set
            {
                m_AStartLevelUniqueName = value;
                m_NeedReload = true;
            }
        }

        private String m_VariableToMDXSet = String.Empty;
        /// <summary>
        /// Глобальная переменная для MDXSet
        /// </summary>
        public String AVariableToMDXSet
        {
            set
            {
                m_VariableToMDXSet = value;
            }
            get
            {
                return m_VariableToMDXSet;
            }
        }
    }
}
